package com.cloudkinto.utils;

import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.data.redis.core.script.RedisScript;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.Collections;

/**
 * Redis 分布式锁
 **/
@Component
@RequiredArgsConstructor
public class RedisLockUtils {

    /**
     * 分布式锁休眠 至 再次尝试获取 的等待时间 ms 可以根据业务自己调节
     */
    public static final Long LOCK_REDIS_WAIT = 500L;
    /**
     * 分布式锁过期时间 s  可以根据业务自己调节
     */
    private static final Long LOCK_REDIS_TIMEOUT = 2L;
    private final RedisTemplate redisTemplate;

    /**
     * 加锁
     *
     * @param key   key
     * @param value 一个随机值，来充当进程的标识
     **/
    public Boolean getLock(String key, String value) {
        return redisTemplate.opsForValue().setIfAbsent(key, value, Duration.ofSeconds(LOCK_REDIS_TIMEOUT));
    }

    /**
     * 释放锁
     **/
    public Long releaseLock(String key, String value) {
        String luaScript = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
        RedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);
        return (Long) redisTemplate.execute(redisScript, Collections.singletonList(key), value);
    }
}
